package com.aaronprj.common.utils;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class CommonEntityManager{

	protected static EntityManagerFactory emf;
	
	  
	public static void verifyEntityManager(){
		if(null == emf){
			emf = Persistence.createEntityManagerFactory("JPAService");
		}
	}
	
	
	
	public static void save(Object obj,boolean isNew){
		verifyEntityManager();
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		if(isNew){
			em.persist(obj);
		}else{
			em.merge(obj);
		}
		em.flush();
		
		em.getTransaction().commit();
		em.close();
	}

	public static void save(Object[] objs){
		verifyEntityManager();
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		for(Object obj:objs){
			em.persist(obj);
			em.flush();
		}
		
		em.getTransaction().commit();
		em.close();
	}
	
	public static <T> T find(Class<T> entityClass, Object primaryKey){

		verifyEntityManager();

		EntityManager em = emf.createEntityManager();
		T obj = em.find(entityClass, primaryKey);
		em.close();
		
		return obj;
	} 
	
	public static List<?> getAllEntities(String entityName){

		verifyEntityManager();

		EntityManager em = emf.createEntityManager();
		List<?> objs = em.createNamedQuery(entityName+".findAll").getResultList();
		em.close();
		
		return objs;
	} 
	
	public static Object getEntity(String namedQuery, String paramName,Object paramValue){

		List<?> objs = getEntities(namedQuery, paramName, paramValue);
		if(null == objs || objs.isEmpty()){
			return null;
		}
		return objs.get(0);
	} 

	
	public static List<?> getEntities(String namedQuery, String paramName,Object paramValue){

		verifyEntityManager();

		EntityManager em = emf.createEntityManager();
		List<?> objs = em.createNamedQuery(namedQuery).setParameter(paramName, paramValue).getResultList();
		em.close();
		
		return objs;
	} 
	
	public static List<?> getEntities(String queryString){

		verifyEntityManager();

		EntityManager em = emf.createEntityManager();
		List<?> objs = em.createQuery(queryString).getResultList();
		em.close();
		
		return objs;
	} 
	

	public static int batchUpdate(String updatequery){

		verifyEntityManager();

		EntityManager em = emf.createEntityManager();
		int ireturn = em.createQuery(updatequery).executeUpdate();
		em.close();
		return ireturn;
		
	} 

}
